function arr2Tree(arr) {
  var arr2map = {}
  var roots = [];

  arr.forEach(element => {
    arr2map[element.id] = element
  });

  arr.forEach(element => {
    if (arr2map[element.pid]) { //利用引用类型构建层级数据
      arr2map[element.pid].children = arr2map[element.pid].children || [];
      arr2map[element.pid].children.push(element);
    } else { // 确定第一层
      roots.push(element)
    }
  })

  return roots


}

let arr = [
  {id: 1, name: '部门1', pid: 0},
  {id: 2, name: '部门2', pid: 1},
  {id: 3, name: '部门3', pid: 1},
  {id: 4, name: '部门4', pid: 3},
  {id: 5, name: '部门5', pid: 4},
]


console.log(arr2Tree(arr))